/*
 *  Copyright (C) 2011 Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * pn_Searcher.java
 *
 * Created on 19/06/2011, 22:37:54
 */
package kuasar.plugin.servermanager.gui.actions;

import java.awt.Color;
import java.awt.Component;
import java.net.InterfaceAddress;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import kuasar.plugin.Intercom.GUI;
import kuasar.plugin.servermanager.gui.pn_Main;
import kuasar.plugin.utils.XML;
import kuasar.plugin.utils.pn_Info;

/**
 *
 * @author Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 */
public class pn_Searcher extends kuasar.plugin.classMod.AbstractPanel {

    private pn_Main main;
    private th_Scan scan;
    private String groupName;
    List<InterfaceAddress> ias = null;
    DefaultTableModel tableModel = createTableModel();
    boolean checkUser;
    String user;
    char[] pass;
    String keyStore;
    char[] kspass;
    boolean dnie;
    int port;

    /** Creates new form pn_Searcher */
    public pn_Searcher(List<InterfaceAddress> ias, int port, String groupName, String keystore, char[] kspass, boolean dnie, String user, char[] pass, boolean checkUser, pn_Main main) {
        this.main = main;
        this.groupName = groupName;
        this.checkUser = checkUser;
        this.user = user;
        this.pass = pass;
        this.keyStore = keystore;
        this.kspass = kspass;
        this.dnie = dnie;
        this.ias = ias;
        this.port = port;
        initComponents();
        spn_Servers.getViewport().setOpaque(false);
        tbl_Servers.setDefaultRenderer(tbl_Servers.getColumnClass(0), new CellRenderer());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        spn_Servers = new javax.swing.JScrollPane();
        tbl_Servers = new javax.swing.JTable();
        pb_Progress = new javax.swing.JProgressBar();
        btn_OK = new javax.swing.JButton();
        lbl_log = new javax.swing.JLabel();
        spn_log = new javax.swing.JScrollPane();
        txa_log = new javax.swing.JTextArea();
        btn_Cancel = new javax.swing.JButton();
        btn_stop = new javax.swing.JButton();

        setOpaque(false);

        spn_Servers.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Servers.setViewportBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Servers.setOpaque(false);

        tbl_Servers.setBackground(new Color(0,0,0,0f));
        tbl_Servers.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        tbl_Servers.setForeground(new java.awt.Color(204, 204, 204));
        tbl_Servers.setModel(tableModel);
        tbl_Servers.setOpaque(false);
        tbl_Servers.setTableHeader(null);
        spn_Servers.setViewportView(tbl_Servers);

        pb_Progress.setString("");
        pb_Progress.setStringPainted(true);

        btn_OK.setBackground(new java.awt.Color(0, 0, 0));
        btn_OK.setForeground(new java.awt.Color(204, 204, 204));
        btn_OK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/dialog-ok-apply.png"))); // NOI18N
        btn_OK.setText("Save");
        btn_OK.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_OK.setEnabled(false);
        btn_OK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_OKActionPerformed(evt);
            }
        });

        lbl_log.setForeground(new java.awt.Color(204, 204, 204));
        lbl_log.setText("Log:");

        txa_log.setColumns(20);
        txa_log.setEditable(false);
        txa_log.setRows(5);
        spn_log.setViewportView(txa_log);

        btn_Cancel.setBackground(new java.awt.Color(0, 0, 0));
        btn_Cancel.setForeground(new java.awt.Color(204, 204, 204));
        btn_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/dialog-cancel.png"))); // NOI18N
        btn_Cancel.setText("Cancel");
        btn_Cancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_CancelActionPerformed(evt);
            }
        });

        btn_stop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/stop.png"))); // NOI18N
        btn_stop.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btn_stop.setBorderPainted(false);
        btn_stop.setContentAreaFilled(false);
        btn_stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_stopActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btn_stop)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pb_Progress, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_Cancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_OK))
                    .addComponent(spn_log, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE)
                    .addComponent(lbl_log, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addComponent(spn_Servers)
                        .addGap(35, 35, 35)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(spn_Servers, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbl_log)
                .addGap(4, 4, 4)
                .addComponent(spn_log)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(pb_Progress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn_OK, javax.swing.GroupLayout.PREFERRED_SIZE, 26, Short.MAX_VALUE)
                    .addComponent(btn_stop, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                    .addComponent(btn_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, Short.MAX_VALUE))
                .addContainerGap(14, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btn_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CancelActionPerformed
        abortSearch();
        GUI.loadPlugin(main);
        GUI.visibleToolBar();
    }//GEN-LAST:event_btn_CancelActionPerformed

    private void btn_stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_stopActionPerformed
        abortSearch();
        enableOK();
    }//GEN-LAST:event_btn_stopActionPerformed

    private void btn_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_OKActionPerformed
        if(saveAll()){
            GUI.loadPlugin(main);
            GUI.visibleToolBar();
        }else{
            pn_Info.Load((JPanel) this.getParent(), this, "Error saving data", "All or some servers detected weren't saved. <p> Check for bad names (Red text) "
                    + "or duplicated names", pn_Info.ICON_ERROR);
        }
        
    }//GEN-LAST:event_btn_OKActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Cancel;
    private javax.swing.JButton btn_OK;
    private javax.swing.JButton btn_stop;
    private javax.swing.JLabel lbl_log;
    private javax.swing.JProgressBar pb_Progress;
    private javax.swing.JScrollPane spn_Servers;
    private javax.swing.JScrollPane spn_log;
    private javax.swing.JTable tbl_Servers;
    private javax.swing.JTextArea txa_log;
    // End of variables declaration//GEN-END:variables

    private boolean saveAll() {
        if(tableModel.getRowCount()==0){
            return true;
        }
        boolean close = true;
        DefaultTableModel tmAux = createTableModel();
        if (!main.addGroup(groupName)) {
            pn_Info.Load((JPanel) this.getParent(), this, "Error saving groupname", "It was impossible to save the groupname.", pn_Info.ICON_ERROR);
            return false;
        }
        main.goTo(groupName);
        for(int i=0; i<tableModel.getRowCount(); i++){
            String name = (String) tableModel.getValueAt(i, 0);
            if(!XML.isCorrectName(name)){
                close = false;
                tmAux.addRow(new Object[]{tableModel.getValueAt(i, 0),tableModel.getValueAt(i, 1)});
            }else{
                if(main.childExists(name)){
                    close = false;
                    tmAux.addRow(new Object[]{tableModel.getValueAt(i, 0),tableModel.getValueAt(i, 1)});
                }else{
                    if(!main.addServer(name, (String) tableModel.getValueAt(i, 1), port)){
                        close = false;
                        tmAux.addRow(new Object[]{tableModel.getValueAt(i, 0),tableModel.getValueAt(i, 1)});
                    }
                }
            }
        }
        tableModel=tmAux;
        tbl_Servers.setModel(tableModel);
        return close;
    }
    
    /* Check ServerNames
     *
     * Return:
     * Rows with bad names;
     * 
     */
    
    private void abortSearch() {
        if (scan != null) {
            if (scan.isAlive()) {
                scan.abort();
                try {
                    scan.join();
                } catch (InterruptedException ex) {
                    System.err.println("serverManager:\t Was impossible to wait scan process");
                }
            }
        }
        btn_OK.setEnabled(true);
    }

    protected void startSearch() {
        scan = new th_Scan(this);
        scan.start();
    }
    
    public void enableOK(){
        btn_OK.setEnabled(true);
    }
    
    private DefaultTableModel createTableModel() {
        return new javax.swing.table.DefaultTableModel(
                new Object[][]{},
                new String[]{
                    "Hostname", "Address"
                }) {

            Class[] types = new Class[]{
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean[]{
                true, false
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        };
    }

    protected void addServer(String name, String IP) {
        tableModel.addRow(new Object[]{name,IP});
    }

    protected void setMaxProgress(int max) {
        pb_Progress.setMaximum(max);
    }

    protected void setProgress(int progress) {
        if (progress < 0) {
            if (!pb_Progress.isIndeterminate()) {
                pb_Progress.setIndeterminate(true);
            }
        } else {
            if (pb_Progress.isIndeterminate()) {
                pb_Progress.setIndeterminate(false);
            }
            pb_Progress.setValue(progress);
        }

    }

    protected void setProgressText(String text) {
        pb_Progress.setString(text);
    }

    protected void hideStop() {
        btn_stop.setVisible(false);
    }

    protected List<InterfaceAddress> getInterfaces() {
        return ias;
    }

    protected void addLog(String message) {
        txa_log.append(message + "\n");
        txa_log.setCaretPosition(txa_log.getText().length());
    }
}
class CellRenderer extends DefaultTableCellRenderer
{
    @Override
   public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row, int column)
   {
      super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
      String name = (String) value;
      if (XML.isCorrectName(name)){
         this.setForeground(new Color(204,204,204));
      }else{
          this.setForeground(Color.red);
      }
      return this;
   }
}
